<template>
  <div class="home_warp">
    <el-card>
      <div slot="header" class="clearfix">
        <el-button
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="clickUserBtn('', 'add')"
          >新增角色</el-button
        >
      </div>
      <el-table
        :data="rolesList"
        style="width: 100%"
        stripe
        border
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
      >
        <el-table-column width="80" type="expand">
          <template v-slot="{ row }">
            <span v-if="row.children.length === 0">
              暂无权限
            </span>
            <el-row
              v-else
              :gutter="20"
              v-for="item in row.children"
              :key="item.id"
              class="item-el-row"
            >
              <!-- type="flex"
              justify="center"
              align="middle" -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(row, item.id)">{{
                  item.authName
                }}</el-tag>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="(item1, index1) in item.children"
                  :key="item1.id"
                  class="item-el-row"
                  :class="{
                    'item1-el-row': index1 === item.children.length - 1
                  }"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(row, item1.id)"
                      >{{ item1.authName }}</el-tag
                    >
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item2 in item1.children"
                      :key="item2.id"
                      closable
                      type="warning"
                      class="pad-tag"
                      @close="removeRightById(row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column width="80" type="index" label="#"></el-table-column>
        <el-table-column width="120" label="角色 ID" prop="id">
        </el-table-column>
        <el-table-column width="300" label="角色名称" prop="roleName">
        </el-table-column>
        <el-table-column width="300" label="角色描述" prop="roleDesc">
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              @click="clickUserBtn(row, 'edit')"
              type="primary"
              icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button
              @click="clickUserBtn(row, 'del')"
              type="danger"
              icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              @click="clickUserBtn(row, 'tree')"
              type="warning"
              icon="el-icon-s-tools"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增,,修改 角色弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      :modal-append-to-body="false"
      :before-close="closeDialog"
    >
      <el-tree
        :data="treeData"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
        @check-change="handleCheckChange"
        v-if="type && type === 'tree'"
      >
      </el-tree>
      <el-form v-else :model="form" :rules="addFromRules" ref="addFormRef">
        <el-form-item
          label="角色名称"
          :label-width="formLabelWidth"
          prop="roleName"
        >
          <el-input v-model="form.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          :label-width="formLabelWidth"
          prop="roleDesc"
        >
          <el-input v-model="form.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitRoles">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getRoles,
  deleteRoles,
  addRoles,
  editRoles,
  allRoles,
  authorizationRoles,
  deleteSpecificRoles
} from '@/api/role'
export default {
  name: 'Role',
  components: {},
  data() {
    return {
      defKeys: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      treeData: [],
      roleId: '',
      title: '',
      type: '',
      rolesList: [],
      dialogFormVisible: false,
      form: {
        roleName: '',
        roleDesc: ''
      },
      formLabelWidth: '120px',
      addFromRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleCheckChange() {},
    closeDialog() {
      const form = {
        roleName: '',
        roleDesc: ''
      }
      this.type = ''
      this.form = form
      this.dialogFormVisible = false
    },

    submitRoles() {
      if (this.type === 'add') {
        this.$refs.addFormRef.validate(valid => {
          console.log(valid)
          if (!valid) {
            return this.$message.warning('名称或描述不合法')
          }
          addRoles(this.form).then(() => {
            this.getRoles()
            this.closeDialog()
          })
        })
      } else if (this.type === 'edit') {
        const { id, roleDesc, roleName } = this.form
        editRoles({
          id,
          data: {
            roleDesc,
            roleName
          }
        }).then(() => {
          this.getRoles()
          this.closeDialog()
        })
      } else if (this.type === 'tree') {
        const idList = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        const rids = idList.join(',')
        authorizationRoles({
          roleId: this.roleId,
          data: {
            rids
          }
        }).then(() => {
          this.getRoles()
          this.closeDialog()
        })
      }
    },
    async getRoles() {
      const { data: res } = await getRoles()
      this.rolesList = res
    },
    clickUserBtn(row, type) {
      if (type === 'del') {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(res => {
            const { id } = row
            deleteRoles(id).then(() => {
              this.getRoles()
            })
          })
          .catch(() => {
            this.$message.info('已取消删除')
          })
      } else if (type === 'edit') {
        this.type = 'edit'
        this.title = '编辑用户'
        this.form = row
        this.dialogFormVisible = true
      } else if (type === 'add') {
        this.type = 'add'
        this.title = '新增角色'
        this.dialogFormVisible = true
      } else if (type === 'tree') {
        this.type = 'tree'
        this.roleId = row.id
        this.title = '分配权限'
        this.getAllRoles(row)
      }
    },
    async getAllRoles(node) {
      const { data: res } = await allRoles(this.type)
      this.treeData = res
      // 递归获取三级节点的id
      this.getLeadfKeys(node, this.defKeys)
      this.dialogFormVisible = true
    },
    // 通过递归的形式,获取角色所有的三级权限的id  并保存到 defKeys 数组中
    getLeadfKeys(node, arr) {
      // 判断有没有子节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeadfKeys(item, arr))
    },
    async removeRightById(row, rightId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await deleteSpecificRoles({
          roleId: row.id,
          rightId
        })
        console.log(res)
        row.children = res
      })
    }
  },
  created() {
    this.getRoles()
  }
}
</script>
<style lang="scss" scoped>
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.bg-purple {
  background: #d3dce6;
}
.item-el-row {
  padding: 10px 0;
  border-bottom: 1px solid #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
}

.item1-el-row {
  border-bottom: none;
}
.pad-tag {
  margin: 5px 10px;
}
</style>
